package com.zjt.smart.mvp.presenter.base;

import com.zjt.smart.bean.CacheBean;
import com.zjt.smart.manager.CacheManager;
import com.zjt.smart.mvp.view.LoadView;

import okhttp3.Request;
import okhttp3.ResponseBody;
import retrofit2.Call;

public abstract class LoadPresenter<DataType> {
    private Call mCall;
    private BaseCallback mCallback;
    public static boolean isActivate = false;
    private static String C;
    private static String K;

    public LoadPresenter() {
        initAPI();
    }

    protected abstract void initAPI();

    protected void doLoading(Call<ResponseBody> call, LoadView<DataType> loadView, boolean fromCache) {
        if (fromCache){
            doCacheLoading(call,loadView);
        } else {
            doRemoteLoading(call,loadView);
        }
    }

    protected void doRemoteLoading(Call call, LoadView<DataType> loadView) {
        mCall = call;
        mCallback = createCallback(mCall,loadView);
        if (mCallback != null){
            mCall.enqueue(mCallback);
        }
    }

    protected void doCacheLoading(Call call, LoadView<DataType> loadView) {
        Request request = call.request();
        mCallback = createCallback(call,loadView);
        CacheManager.getInstance().readCacheAsync(request, cache -> {
            if (mCallback == null){
                return;
            }
            if (cache != null){
                mCallback.onLoadCache(cache.getTime(), cache.getResponse());
            }else {
                mCallback.onLoadCache(0, null);
            }
        });
        CacheBean cache = CacheManager.getInstance().readCache(request);
        if (mCallback != null && cache != null){
            if (cache != null){
                mCallback.onLoadCache(cache.getTime(), cache.getResponse());
            }else {
                mCallback.onLoadCache(0, null);
            }
        }
    }

    public void destroy(){
        if (mCall != null){
            if (!mCall.isCanceled()) mCall.cancel();
            mCall = null;
        }
        if (mCallback != null){
            mCallback = null;
        }
    }

    protected abstract BaseCallback createCallback(Call<ResponseBody> call, LoadView<DataType> loadView);


}
